#include "apue.h"
#include <syslog.h>
#include <pthread.h>

sigset_t mask;

extern int already_running();
extern void daemonize(char *cmd);

void reread(void) {
    openlog("adv_unix_program_13_7",LOG_PID|LOG_CONS, LOG_DAEMON);
    syslog(LOG_ERR, "reread configuration file");
}

void *thr_fn(void *arg) {
    syslog(LOG_ERR, "ab");
    int err, signo;
    for (;;) {
        if ((err= sigwait(&mask, &signo)) > 0) {
            syslog(LOG_ERR, "signal failed");
            exit(1);
        }
        switch(signo) {
            case SIGTERM:
                syslog(LOG_INFO, "got SIGTERM; exiting");
                exit(0);
                break;

            case SIGHUP:
                syslog(LOG_INFO, "sig: SIGHUP");
                reread();
                break;

            default:
                syslog(LOG_INFO, "unexpected signal %d\n", signo);
        }
        
    }
    return (0);
}

int main(int argc, char *argv[]) {
    int err;
    char *cmd;
    pthread_t tid;
    struct sigaction sa;

    if ((cmd= strrchr(argv[0], '/')) != NULL)
        cmd= argv[0];
    else
        cmd++; 

    syslog(LOG_ERR, "kakaxi");

    //if (already_running()) {
    //    syslog(LOG_ERR, "daemon already running");
    //    exit(1);
    //}
    daemonize(cmd);

    sa.sa_handler= SIG_DFL;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags= 0;
    if (sigaction(SIGHUP, &sa, NULL) != 0)
        err_quit("%s: cant restore SIGHUP default");    /* stdin had close, so no output */

    sigfillset(&mask);
    if ((err= pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
        err_exit(err, "SIG_BLOCK error");

    if ((err= (pthread_create(&tid, NULL, thr_fn, NULL))) != 0)
        err_exit(err, "pthread_create error");

    sleep(10000);

    /**
     * proceed with the rest of the daemon
     */
    exit(0);
}
